<!--传入一个function用来接index；传入一个数组用来渲染tab内容-->
<template>
  <div id="box">
    <ul>
      <li v-for="(item, index) in tabLine" @click="chose(index)" :class="{'active':choseBar==index}">
        <a ref="lump">{{item.name}}</a>
      </li>
    </ul>
    <em ref="float"></em>
  </div>
</template>

<script type="text/javascript">
  export default{
    data () {
      return {
        choseBar: 0
      }
    },
    props: {
      tabLine: {
        type: Array,
        default: function () {
          return [{name: 'item1'}, {name: 'item2'}]
        }
      },
      onSelected: {
        type: Function
      },
      selectIndex: {
        default: 0
      }
    },
    methods: {
      chose (index) {
        if (this.choseBar !== index) {
          this.choseBar = index
        }
        this.slide(true);
      },
      fn () {
        this.onSelected(this.choseBar)
        this.$refs.float.removeEventListener('webkitTransitionEnd', this.fn)
      },
      slide(excute) {
        this.$refs.float.style.width = this.$refs.lump[this.choseBar].offsetWidth + 'px'
        this.$refs.float.style.left = this.$refs.lump[this.choseBar].offsetLeft + 'px'
        if (excute) {
          this.$refs.float.addEventListener('webkitTransitionEnd', this.fn)
        }
      }
    },
    watch: {
      tabLine: {
        handler: function() {
          this.$nextTick(() => {
            this.slide()
          })
        },
        deep: true
      }
    },
    created () {
      this.choseBar = this.selectIndex
    },
    mounted () {
      this.slide();
    }
  }
</script>

<style lang="less" scoped>
  #box{
    display:flex;
    background: white;
    justify-content:center;
    font-size: .14rem;
    height:0.36rem;
    border-bottom: solid 1px #eaeaea;
    position: relative;
    em {
      transition: .3s ease all;
      content: '';
      position: absolute;
      bottom: -1px;
      display: block;
      height: 2px;
      background: #2f9fe9;
    }
  }
  ul{
    width:90%;
    padding:0;
    margin: 0;
    height:0.36rem;
    display:flex;
    flex-direction:row;
    flex-wrap:nowrap;
  }
  li{
    box-sizing: border-box;
    list-style:none;
    height:0.36rem;
    font-size: .14rem;
    line-height: 0.36rem;
    a{
      white-space: nowrap;
      /*max-width: calc(100% - 34px);*/
      display: inline-block;
      padding: 0 17px;
    }
  }
  li:last-child{
    border:none;
  }
  li.active{
    color:#2f9fe9;
  }
</style>
